﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using IRUM.Core;
using IRUM.XingAPI;
using IRUM.Utils;

namespace IRUM.TR
{
    /// <summary>
    /// 시총상위종목
    /// </summary>
    public class TopStock
    {
        public string date = string.Empty;      //"yyyymmdd"
        public string upcode = string.Empty;    //업종코드, 001, 301
        public int idx = 0;                     //시총순위
        public string shcode = string.Empty;    //종목코드
        public string hname = string.Empty;     //종목명
        public long price = 0;                  //현재가
        public long change = 0;                 //전일대비
        public float diff = 0;                  //등락율
        public long volume = 0;                 //거래량
        public float vol_rate = 0;              //거래비중
        public long total = 0;                  //시가총액
        public float rate = 0;                  //비중
        public float for_rate = 0;              //외인비중
    }

    public class TopStockArgs : EventArgs
    {
        public List<TopStock> RetData = null;

        public TopStockArgs(List<TopStock> data)
        {
            RetData = data;
        }
    }

    public delegate void TopStockHandler(object s, TopStockArgs e);

    /// <summary>
    /// 시가총액 상위종목 조회
    /// </summary>
    public class t1444 : CBaseQuery
    {
        public event TopStockHandler OnReceived;
        private List<TopStock> m_list = new List<TopStock>();

        private string upcode = string.Empty;
        private int count = 100;
        private string idx = " ";
        private int index = 1;

        /// <summary>
        /// 시가총액 상위종목 조회
        /// </summary>
        /// <param name="upcode">업종코드</param>
        public t1444(string upcode)
        {
            this.upcode = upcode;

            SetClassData(TR_Type.t1444);
        }

        public void SetOutBlockData(int Index)
        {
            TopStock ts = new TopStock();

            ts.date = IRUM_Utils.GetLastTradingDateForDay(DateTime.Now).ToString("yyyyMMdd");    //마지막 거래일 가져와서 처리해야 함.
            ts.upcode = upcode;
            ts.idx = index++;
            ts.shcode = m_Query.GetFieldData(m_OutBlock1Name, "shcode", Index);
            ts.hname = m_Query.GetFieldData(m_OutBlock1Name, "hname", Index);
            ts.price = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "price", Index));
            ts.change = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "change", Index));
            ts.diff = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "diff", Index));
            ts.volume = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "volume", Index));
            ts.vol_rate = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "vol_rate", Index));
            ts.total = Convert.ToInt64(m_Query.GetFieldData(m_OutBlock1Name, "total", Index));
            ts.rate = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "rate", Index));
            ts.for_rate = Convert.ToSingle(m_Query.GetFieldData(m_OutBlock1Name, "for_rate", Index));

            if (ts.diff < 0)
            {
                ts.change = ts.change * -1;
            }

            m_list.Add(ts);
        }

        public override void HandleQuery()
        {
            int OccursCount = m_Query.GetBlockCount(m_OutBlock1Name);

            for (int OccursIndex = 0; OccursIndex < OccursCount; OccursIndex++)
            {
                try
                {
                    SetOutBlockData(OccursIndex);
                }
                catch (Exception e)
                {
                    Debug.Print(e.ToString());
                    continue;
                }
            }

            //연속조회
            if (m_Query.IsNext == true && m_list.Count < count)
            {
                idx = m_Query.GetFieldData(m_OutBlockName, "idx", 0);
                RequestNext();
            }
            else
            {
                // 이벤트 발생
                if (OnReceived != null)
                {
                    OnReceived(this, new TopStockArgs(m_list));
                }
            }
        }

        protected override void SetRequestData()
        {
            m_Query.SetFieldData(m_InBlockName, "upcode", 0, upcode);       //업종코드, 3
            m_Query.SetFieldData(m_InBlockName, "idx", 0, idx);             //Index, 4, 처음조회시 Space, 연속조회시 Outblock의 idx
        }
    }
}
